package com.foreveross.chameleon.socket;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.foreveross.chameleon.base.PushApplication;
import com.foreveross.chameleon.utils.DeviceInfoUtil;
import com.foreveross.chameleon.utils.Preferences;
import com.foreveross.chameleon.utils.PushConstants;
import com.foreveross.chameleon.utils.PushPreferences;
import com.foreveross.chameleon.utils.httputil.HttpConnection;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * project:
 * author: wzq
 * date: 2014/7/21
 * description: http token管理 : 获取、删除
 */
public class TokenGetter {
    private static final int MAX_RETRY_TIME_FOR_TOKEN = 3;//获取token失败尝试次数
    private String userName = null;

    public static void clearCurrToken() {
        PushPreferences preferences = new PushPreferences();
        preferences.saveToken("");
    }

    public interface OnTokenGetted {
        void tokenGetted(String token, String userName);// 获取token后的回调
    }

    /**
     * 异步进行，完成后回调，请在线程中处理
     * 如果返回null or "",则表明不能正确获取token
     */
    public void getToken(final OnTokenGetted tokenGetCallback) {

        // http 获取token的线程
        new Thread() {
            public void run() {
                String token = getLocalValidToken();
                //AppLog.i("local token=" + token);
                if (null == token || "".equals(token)) {
                    //TODO http获取token
                    //AppLog.e("本地token 无效，尝试网络获取token");
                    token = http4Token();
                }

                final String resultToken = token;
                //AppLog.i("token=" + resultToken);
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (tokenGetCallback != null) {
                            tokenGetCallback.tokenGetted(resultToken, userName);
                        }
                    }
                });
            }
        }.start();
    }

    // 获取保持在本地的，有效的token，null表示无token 或者无效(会清除token)
    private String getLocalValidToken() {
        PushPreferences preferences = new PushPreferences();
        String push_token = preferences.getToken();
        userName = preferences.getUserName();
        if ("".equals(push_token) || isExpired()) {
            // TODO token无效，清除
            clearCurrToken();
            push_token = null;
        }
        return push_token;
    }

    /**
     * 判断PushToken是否过期
     *
     * @return
     */
    private boolean isExpired() {
        try {
            PushPreferences preferences = new PushPreferences();
            String tokenCreateDate = preferences.getTokenCreateTime();
            int expiredTime = preferences.getExpiedTime();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            Date d = format.parse(tokenCreateDate);
            Calendar cNow = Calendar.getInstance();
            Calendar cD = Calendar.getInstance();
            cD.setTime(d);
            cD.add(Calendar.DAY_OF_MONTH, expiredTime);
            int c = cD.compareTo(cNow);
            if (c > 0) {
                return false;
            } else {
                return true;
            }
        } catch (ParseException e) {
            return true;
        }
    }

    // http通讯获取token
    private String http4Token() {
        //Context context = ChameleonApplication.getApplication();
        Context context = PushApplication.getApplication();
        //PropertiesUtil propertiesUtil = PropertiesUtil.readProperties(context, CubeConstants.CUBE_CONFIG);

        // 准备上送参数
        //String server_host = propertiesUtil.getString("push_server_host", "");
        //String server_port = propertiesUtil.getInteger("push_server_port", 0) + "";
        //String appId = propertiesUtil.getString("appKey", null);
        //String secret = propertiesUtil.getString("secret", null);
//        String server_host = PushConstants.PUSH_SERVER_HOST;
//        String server_port = PushConstants.PUSH_SERVER_PORT + "";
        String appId = PushConstants.APPKEY;
        String secret = PushConstants.SECRET;
        String currentUser;
        currentUser = Preferences.getUserName();
        if (currentUser == null || currentUser.equals("")) {
            currentUser = "guest";
        }

        // 准备通讯参数
        final String url = PushConstants.INSTANT_URL;
//        final String url = "http://" + server_host + ":" + server_port + "/authenticate";
        final List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("appId", appId));
        params.add(new BasicNameValuePair("secret", secret));
        params.add(new BasicNameValuePair("username", currentUser));
        params.add(new BasicNameValuePair("deviceId", DeviceInfoUtil.getDeviceId()));
        //AppLog.i("Try to tokenGetted Push Token____ " + currentUser);

        // 开始通讯 尝试若干次
        int remainRetry = 1;
        String token = null;
        while (token == null && remainRetry <= MAX_RETRY_TIME_FOR_TOKEN) {
            //AppLog.i("获取token,第 " + remainRetry + " 次尝试");
            remainRetry++;
            String jsonStr = HttpConnection.post(url, params);
            token = handleTokenJson(jsonStr);
        }
        return token;
    }

    // 处理http返回的json
    private String handleTokenJson(String jsonStr) {
        if (jsonStr == null) {
            return null;
        }

        String push_token = null;
        try {
            JSONObject object = new JSONObject(jsonStr);
            if (object.getBoolean("result")) {
                String tempHost = object.getString("host");
                int tempPort = object.getInt("port");
                push_token = object.getString("push_Token");
                String tokenCreateDate = object.getString("expired");
                int expiredTime = object.getInt("expired_day");

                // save
                PushPreferences preferences = new PushPreferences();
                preferences.saveExpiredTime(expiredTime);
                preferences.saveToken(push_token);
                preferences.saveTokenCreateTime(tokenCreateDate);
                preferences.saveTempHost(tempHost);
                preferences.saveTempPort(tempPort);
            }
        } catch (JSONException e) {
            // 服务端格式不合法
            e.printStackTrace();
            //AppLog.e("服务端格式不合法 token 格式不合法 " + jsonStr.toString());
            push_token = null;
        }
        return push_token;
    }
}
